package com.jemmyee.pizza.web.controller;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jemmyee.core.dao.Page;
import com.jemmyee.core.web.controller.BaseController;
import com.jemmyee.pizza.entity.CaiType;
import com.jemmyee.pizza.entity.Dept;
import com.jemmyee.pizza.service.ICaiTypeService;
import com.jemmyee.pizza.web.Constants;
import com.jemmyee.pizza.web.utils.CategoryXmlUtils;


/**
 * @Description:部门管理
 * @author:jemmyee@gmail.com
 * @date:2010-10-28
 * @version:v1.0
 */
@Controller
@RequestMapping("/admin/caitype")
public class CaiTypeController extends BaseController{
	
	private static Log log= LogFactory.getLog(CaiTypeController.class);
	
	@Autowired
	private ICaiTypeService<CaiType> caiTypeService;
	

	@RequestMapping("/frame")
	public ModelAndView frame(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("/admin/caitype/frame");
		return mv;
	}
	@RequestMapping("/tree")
	public ModelAndView tree(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("/admin/caitype/tree");
		createTreeXml(request);
		return mv;
	}
	@RequestMapping("/right/{id}")
	public ModelAndView right(@PathVariable Integer id,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.addObject("items", caiTypeService.findByProperty("fatherId",id));
		request.getSession().setAttribute("session_caitype_id",id);
		mv.addObject("caitype", caiTypeService.findById(id));
		mv.setViewName("/admin/caitype/right");
		return mv;
	}
	@RequestMapping("/welcome")
	public ModelAndView welcome(){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("/admin/caitype/welcome");
		return mv;
	}
	
	
	@RequestMapping("/to_add")
	public ModelAndView toAdd(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("/admin/caitype/add");
//		mv.addObject("depts", caiTypeService.findByProperty("fatherId",0));
		Integer fid=Integer.parseInt(request.getSession().getAttribute("session_caitype_id").toString());
		mv.addObject("fid", fid);
		return mv;
	}
	
	@RequestMapping("/to_edit/{id}")
	public ModelAndView toEdit(@PathVariable Integer id,HttpServletRequest request){
		   ModelAndView mv=new ModelAndView();
		   mv.setViewName("/admin/caitype/edit");
		   mv.addObject("caitype", caiTypeService.findById(id));
//		   mv.addObject("depts", caiTypeService.findByProperty("fatherId",0));
		Integer fid=Integer.parseInt(request.getSession().getAttribute("session_caitype_id").toString());
		mv.addObject("fid", fid);
		   return mv;
	}
	
	@RequestMapping("/add")
	@ResponseBody
	public Map<String, Object> add(@RequestBody CaiType dept,HttpServletRequest request)
	{   
		Map<String, Object> model = new HashMap<String, Object>();
		CaiType temp=null;
		if(caiTypeService.findByProperty("name",dept.getName())!=null&&caiTypeService.findByProperty("name",dept.getName()).size()>0){
			temp=caiTypeService.findByProperty("name",dept.getName()).get(0);
		}
		if(temp!=null&&temp.getName().equals(dept.getName().trim()))
		{
			model.put("msg","error");
		}else
		{
			dept.setSort(0);
			dept.setStatus(Short.valueOf("0"));
			dept.setFatherId(Integer.parseInt(request.getSession().getAttribute("session_caitype_id").toString()));
			caiTypeService.save(dept);
			model.put("msg","succ");
		}
		return model;
	}


	@RequestMapping("/edit")
	@ResponseBody
	public Map<String, Object> edit(@RequestBody CaiType dept,HttpServletRequest request)
	{   
		Map<String, Object> model = new HashMap<String, Object>();
		CaiType temp=null;
		if(caiTypeService.findByProperty("name",dept.getName())!=null&&caiTypeService.findByProperty("name",dept.getName()).size()>0){
			temp=caiTypeService.findByProperty("name",dept.getName()).get(0);
		}
		CaiType real=caiTypeService.findById(dept.getId());
		if(temp!=null&&temp.getName().equals(dept.getName().trim())&&!temp.getName().equals(real.getName()))
		{
			model.put("msg","error");
		}else
		{
			real.setName(dept.getName());
//			real.setRemark(role.getRemark());
			caiTypeService.update(real);
			model.put("msg","succ");
		}
		return model;
	}

	
	@RequestMapping(value="/list/{startIndex}")
	public ModelAndView list(@PathVariable Integer startIndex,HttpServletRequest request){
		   DetachedCriteria dc= DetachedCriteria.forClass(CaiType.class);
		   ModelAndView mv=new ModelAndView();
		   Page page=caiTypeService.findPageByCriteria(dc,Constants.DEFAULT_PAGESIZE, startIndex,null);
		   mv.addObject("page",page);
		   mv.setViewName("/admin/caitype/list");
		   return mv;
	}
	@RequestMapping(value="/delete/{id}")
	public String delete(@PathVariable Integer id,HttpServletRequest request){
	    caiTypeService.delete(caiTypeService.findById(id));
	    Integer fid=Integer.parseInt(request.getSession().getAttribute("session_caitype_id").toString());
	    return "redirect:/admin/caitype/right/"+fid;
	}
	

	public String createTreeXml(HttpServletRequest request){
		List<CaiType> depts=caiTypeService.findAll();
		String filePath=getAppRoot(request)+Constants.CATEGORY_XML_FILE_PATH+File.separator+Constants.CATEGORY_XML_CAITYPE_NAME;
	    CategoryXmlUtils.createCaiTypeXml(filePath, depts);
		return "ok";
	}
	
	
	@RequestMapping("/dept_tree")
	@ResponseBody
	public Map<String, Object> deptTreeContent(HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		List<CaiType> depts = caiTypeService.findAll();
		StringBuffer sb = new StringBuffer();
		sb.append("<li id='10000' rel='" + getWebURL(request)
				+ "admin/caitype/right/0'>");
		sb.append("<a href='" + getWebURL(request)
				+ "admin/caitype/right/0' target='main'>所有分类</a><ul>");
//		CaiType root=caiTypeService.findByProperty("fatherId",0).get(0);
//		sb.append("<li id='10000' rel='" + getWebURL(request)
//				+ "admin/caitype/right/"+root.getId()+"'>");
//		sb.append("<a href='" + getWebURL(request)
//				+ "admin/caitype/right/"+root.getId()+"' target='main'>"+root.getName()+"</a><ul>");
//		
		List<CaiType> ones=caiTypeService.findByProperty("fatherId",0);
		for (CaiType one:ones) {
			
			sb.append("<li rel='" + getWebURL(request) + "admin/caitype/right/"
					+ one.getId() + "'><a href='" + getWebURL(request)
					+ "admin/caitype/right/" + one.getId()
					+ "' target='treeRight'>" + one.getName() + "</a><ul>");
			List<CaiType> twos=caiTypeService.findByProperty("fatherId",one.getId());
			for (CaiType two:twos) {
				sb.append("<li rel='" + getWebURL(request) + "admin/caitype/right/"
						+ two.getId() + "'><a href='" + getWebURL(request)
						+ "admin/caitype/right/" + two.getId()
						+ "' target='treeRight'>" + two.getName() + "</a><ul>");
				
				List<CaiType> threes=caiTypeService.findByProperty("fatherId",two.getId());
				for (CaiType three:threes) {
					sb.append("<li rel='" + getWebURL(request) + "admin/caitype/right/"
							+ three.getId() + "'><a href='" + getWebURL(request)
							+ "admin/caitype/right/" + three.getId()
							+ "' target='treeRight'>" + three.getName() + "</a><ul>");
					
					List<CaiType> fours=caiTypeService.findByProperty("fatherId",three.getId());
					for (CaiType four:fours) {
						sb.append("<li rel='" + getWebURL(request) + "admin/caitype/right/"
								+ four.getId() + "'><a href='" + getWebURL(request)
								+ "admin/caitype/right/" + four.getId()
								+ "' target='treeRight'>" + four.getName() + "</a></li>");
						
					}
					sb.append("</ul></li>");
					
				}
				sb.append("</ul></li>");
			}
			sb.append("</ul></li>");
		}
		sb.append("</ul></li>");
		model.put("tree", sb.toString());
		return model;
	}
}
